<template>
  <div class="dst-add-card-wrap dstform--demo-wrap" v-loading="loading">
    <div :class="[modeType != 'detail' ? 'dst-add-overflow-y-box' : '']">
      <el-card>
        <div slot="header">
          <span class="dst-card-title">基础信息</span>
        </div>
        <div style="margin: 20px 0">
          <el-button type="success">
            <router-link to="/template/addEditDetail?type=add"
              >点击切换到 添加模式</router-link
            >
          </el-button>
          <el-button type="success">
            <router-link to="/template/addEditDetail?type=edit&id=111"
              >点击切换到 编辑模式</router-link
            >
          </el-button>
          <el-button type="success">
            <router-link to="/template/addEditDetail?type=detail&id=111"
              >点击切换到 详情模式</router-link
            >
          </el-button>
          <el-button
            type="success"
            @click="
              () => {
                showDialog = true;
                showType = 'templateStr1';
              }
            "
          >
            显示代码
          </el-button>
          <span
            >基于dstForm做的集：添加、编辑、详情一套实现代码的模板。路径@/portal-common/commonPage/template/detailAndAddCard/addEditDetail/index.vue</span
          >
        </div>
        <dstForm
          ref="dataArrBase"
          :data-arr="dataArrBase"
          v-model="ruleForm"
          :mode-type="modeType"
          label-width="120px"
        >
        </dstForm>
      </el-card>
      <el-card>
        <div slot="header">
          <span class="dst-card-title">加装项信息</span>
        </div>
        <DstTable
          :table-list="tableList"
          :table-head="tableHeadersArr"
          :config="config"
        />
      </el-card>
      <el-card>
        <div slot="header">
          <span class="dst-card-title">附件</span>
        </div>
        <dstForm
          ref="dataArrfile"
          :data-arr="dataArrfile"
          v-model="ruleForm"
          :mode-type="modeType"
          label-width="100px"
        >
        </dstForm>
      </el-card>
      <dstDialog
        v-if="showDialog && showType == 'addRefitItems'"
        :title="showDialogTitle"
        @beforeClose="handleClose"
        @beforeSure="confrim"
      >
        <dst-form
          ref="formDialog"
          v-model="ruleFormDialog"
          :data-arr="dataArrDialog"
          label-width="130px"
        />
      </dstDialog>
      <el-dialog
        v-if="showDialog && showType == 'templateStr1'"
        title="代码"
        :visible.sync="showDialog"
        width="80%"
      >
        <code class="code-div">
          <pre>{{ templateStr1 }}</pre>
        </code>
        <span slot="footer" class="dialog-footer">
          <el-button @click="showDialog = !showDialog">关闭</el-button>
        </span>
      </el-dialog>
      <div class="dst-add-bottom-btn-box" v-if="modeType != 'detail'">
        <el-button
          type="success"
          v-debounceClick="1500"
          @click="submitFormDstForm"
          >提交</el-button
        >
      </div>
    </div>
  </div>
</template>
<script>
import { dataArrBase, dataArrfile, dataArrDialog } from "./functions/data.js";
import { setTableHeadArr } from "./functions/table.js";
import { templateStr1 } from "@/portal-common/commonPage/template/detailAndAddCard/addEditDetail/functions/template";
import {
  constList,
  createCar,
  updateCar,
  getDetail,
} from "@/portal-common/commonPage/template/detailAndAddCard/addEditDetail/functions/mock.js";
export default {
  name: "detailAndAddCardAddEditDetail",
  components: {},
  data() {
    return {
      modeType: "add",
      loading: false,
      showType: "",
      showDialog: false,
      showDialogTitle: "",
      ruleForm: {
        status: 1,
      },
      ruleFormDialog: {},
      config: {
        isNoPage: true,
        isAutoHeight: false,
      },
      tableList: [],
      tableHeadersArr: setTableHeadArr(this),
      selectData: {
        urgentLevelArr: [],
        statusArr: [],
        refitModeArr: [],
        refitTypeArr: [],
        refitSkuArr: [],
      },
      templateStr1: templateStr1,
    };
  },
  computed: {
    dataArrBase: dataArrBase.bind(this),
    dataArrfile: dataArrfile.bind(this),
    dataArrDialog: dataArrDialog.bind(this),
  },
  mounted() {
    this.init();
    this.initTitle();
    if (this.$route.query.id) {
      this.getDetail();
    }
  },
  methods: {
    handleClose() {
      this.showDialog = false;
      this.showType = "";
      this.ruleFormDialog = {};
    },
    confrim() {
      this.$refs.formDialog.formValidate((valid) => {
        if (valid) {
          this.tableList.push(this.ruleFormDialog);
          this.handleClose();
        }
      });
    },
    init() {
      Promise.all([constList()]).then((res) => {
        this.selectData.urgentLevelArr = res[0].data.refit_project_urgent_level;
        this.selectData.statusArr = res[0].data.refit_project_status;
        this.selectData.refitModeArr = res[0].data.refit_project_refit_mode;
        this.selectData.refitTypeArr = res[0].data.car_sku_refit_range_type;
      });
    },
    initTitle() {
      let title = {
        add: "新建xxxxx",
        edit: "编辑xxxxx",
        detail: "xxxxx详情",
      };
      this.modeType = this.$route.query.type || "add";
      this.$route.meta.title = title[this.modeType];
      this.$store.dispatch("editVisitedViews", this.$route);
    },
    submitFormDstForm() {
      let valid1 = false;
      let valid2 = false;
      this.$refs.dataArrBase.formValidate(async (valid) => {
        valid1 = valid;
      });
      this.$refs.dataArrBase.formValidate(async (valid) => {
        valid2 = valid;
      });
      if (!this.tableList.length) {
        this.$message.error("请至少添加一项加装项");
        return;
      }
      if (valid1 && valid2) {
        const params = {
          ...this.ruleForm,
          implementStartDate: this.ruleForm.date[0], // 实施开始日期
          implementEndDate: this.ruleForm.date[1], // 实施结束日期
          refitItems: this.tableList,
          refitFiles: this.ruleForm.refitFiles.map((item) => {
            return {
              fileType: 1, // 附件类型（1-加装项目，2-加装工单）
              fileName: item.fileName,
              fileUrl: item.saveUrl,
            };
          }),
        };
        let fn = createCar;
        let text = "新增";
        if (this.$route.query.type == "edit") {
          fn = updateCar;
          text = "编辑";
          params.id = this.$route.query.id;
        }
        this.loading = true;
        fn(params)
          .then((res) => {
            this.$message.success(`${text}成功`);
            this.$store
              .dispatch("delVisitedViews", this.$route)
              .then((view) => {
                this.$router.push({
                  path: "/carModified/carAccessory/project",
                });
              });
          })
          .finally(() => {
            this.loading = false;
          });
      } else {
        this.$message.error("请检查表单");
      }
    },
    getDetail() {
      getDetail({
        id: this.$route.query.id,
      }).then((res) => {
        this.ruleForm = res.data;
        if (this.modeType != "detail") {
          this.ruleForm.date = [
            res.data.implementStartDate,
            res.data.implementEndDate,
          ];
        } else {
          this.ruleForm.date =
            res.data.implementStartDate + "至" + res.data.implementEndDate;
        }
        this.tableList = res.data.refitItems;
      });
    },
  },
};
</script>
<style lang="scss"></style>
